package com.revenant.driver.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.OilBean;
import com.revenant.driver.bean.ShipperBean.FaPiaoTaiTouDetailBen;
import com.revenant.driver.utils.Constants;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import wendu.dsbridge.DWebView;

import static android.view.KeyEvent.KEYCODE_BACK;

public class OilWebActivity extends BaseActivity {
    @BindView(R.id.mywalletweb)
    DWebView mywalletweb;
    private Context context;

    @Override
    public int getContentViewResId() {
        context = this;
        return R.layout.activity_oil_web;
    }

    @Override
    public void initView() {
        setcenterTitle("我的油卡");
        getUrl();
//        String maywallweburl = weburlwallet + SPUtils.getAccounId(context);
//        mywalletweb.loadUrl(maywallweburl);

//        //声明WebSettings子类
//        WebSettings webSettings = mywalletweb.getSettings();
//
////如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
//        webSettings.setJavaScriptEnabled(true);
//// 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
//// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可
//
////支持插件
//
////设置自适应屏幕，两者合用
//        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//
////缩放操作
//        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
//        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
//        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//
////其他细节操作
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
//        webSettings.setAllowFileAccess(true); //设置可以访问文件
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
//        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
//        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
    }


    @Override
    public void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && mywalletweb.canGoBack()) {
            mywalletweb.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getUrl() {
        showDig();
        OkGo.<String>post(Constants.Find_Oil_New_Login)
                .params("mobile", SPUtils.getUsermobile(context))
                .execute(new StringCallback() {
                             @Override
                             public void onSuccess(Response<String> response) {
                                 FaPiaoTaiTouDetailBen detailBen = GsonUtil.parseJsonWithGson(response.body(), FaPiaoTaiTouDetailBen.class);
                                 Integer integer = Integer.valueOf(detailBen.getCode().trim());
                                 switch (integer) {
                                     case 0:
                                         Map<String, String> map = new HashMap<>();
//                            map.put("userPhone", SPUtils.getUsermobile(context));
                                         map.put("userPhone", SPUtils.getUsermobile(context));
                                         JSONObject jsonObject = new JSONObject(map);
                                         getH5Url(jsonObject);
                                         break;
                                     case 1:
                                         showLongToast(detailBen.getMsg());
                                         dismissDig();
                                         finish();
                                         startActivity(DriverOilApplyActivity.class);
                                         break;
                                     case 2:
                                         showLongToast(detailBen.getMsg());
                                         dismissDig();
                                         break;
                                     case -1:
                                         showLongToast(detailBen.getMsg());
                                         dismissDig();
                                         break;
                                 }
                             }

                             @Override
                             public void onError(Response<String> response) {
                                 super.onError(response);
                                 dismissDig();
                             }
                         }
                );
    }

    private void getH5Url(JSONObject json) {
        OkGo.<String>post(Constants.Find_Oil_H5)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OilBean detailBen = GsonUtil.parseJsonWithGson(response.body(), OilBean.class);
                        if (detailBen.getCode().equals("0")) {
                            String timestamp = String.valueOf(DateUtil.current(false));//
                            Map<String, String> header = new HashMap<>();
                            header.put("sign", SecureUtil.md5(SecureUtil.md5(SecureUtil.md5(timestamp) + timestamp) + timestamp));
                            header.put("X-Token", SPUtils.getUserToken(App.getApplication()));
                            header.put("timestamp", timestamp);
                            if (detailBen.getData()!=null){
                                mywalletweb.loadUrl(detailBen.getData().getReqestH5Address(),header);
                            }else {
                                dismissDig();
                            }
                            mywalletweb.setWebChromeClient(new WebChromeClient() {
                                public void onProgressChanged(WebView view, int progress) {
                                    if (progress == 100) {
                                        //加载完成
                                        dismissDig();
                                    }
                                }
                            });
                        } else {
                            dismissDig();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

}
